import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import {
  LoginUsers, Hospitals, Departments, Doctors, Orders, Appoints
} from './data/data'
import {base} from '@/api/api'
export default {
  /**
   * mock start
   */
  start () {
    let mock = new MockAdapter(axios)
    let createRandDelay = (min = 400, max = 1000) => Math.ceil(Math.random() * (max - min)) + min  // 随机延迟 400 - 1000 ms
    // user login
    mock.onPost(`${base}/login`).reply(config => {
      let {username, password} = JSON.parse(config.data)
      return new Promise((resolve, reject) => {
        let user = null
        setTimeout(() => {
          let hasUser = LoginUsers.some(u => {
            if (u.username === username && u.password === password) {
              user = JSON.parse(JSON.stringify(u))
              user.password = undefined
              return true
            }
          })
          if (hasUser) {
            resolve([200, {code: 200, msg: 'Login Success!', user}])
          } else {
            resolve([200, {code: 500, msg: 'username or password invalid!'}])
          }
        }, createRandDelay())
      })
    })

    mock.onPost(`${base}/hospitals`).reply(config => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (Hospitals.length !== 0) {
            resolve([200, {code: 200, msg: 'get success', Hospitals}])
          } else {
            resolve([200, {code: 500, msg: 'some error'}])
          }
        }, createRandDelay())
      })
    })

    mock.onPost(`${base}/departments`).reply(config => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (Departments.length !== 0) {
            resolve([200, {code: 200, msg: 'get success', Departments}])
          } else {
            resolve([200, {code: 500, msg: 'some error'}])
          }
        }, createRandDelay())
      })
    })
    mock.onPost(`${base}/doctors`).reply(config => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (Doctors.length !== 0) {
            resolve([200, {code: 200, msg: 'get success', Doctors}])
          } else {
            resolve([200, {code: 500, msg: 'some error'}])
          }
        }, createRandDelay())
      })
    })
    mock.onPost(`${base}/orders`).reply(config => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (Orders.length !== 0) {
            resolve([200, {code: 200, msg: 'get success', Orders}])
          } else {
            resolve([200, {code: 500, msg: 'some error'}])
          }
        }, createRandDelay())
      })
    })
    mock.onPost(`${base}/appoints`).reply(config => {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (Appoints.length !== 0) {
            resolve([200, {code: 200, msg: 'get success', Appoints}])
          } else {
            resolve([200, {code: 500, msg: 'some error'}])
          }
        }, createRandDelay())
      })
    })
  }
}
